package com.c2b.algorithm.leetcode.jzoffer;

import java.util.Stack;

/**
 * <a href="https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&tqId=23290&ru=%2Fpractice%2F4c776177d2c04c2494f2555c9fcc1e49&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&sourceUrl=">栈的压入、弹出序列</a>
 * <p>输入两个整数序列，第一个序列表示栈的压入顺序，请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。</p>
 * <p>例如序列1,2,3,4,5是某栈的压入顺序，序列4,5,3,2,1是该压栈序列对应的一个弹出序列，但4,3,5,1,2就不可能是该压栈序列的弹出序列。</p>
 * 1. 0<=pushV.length == popV.length <=1000<br>
 * 2. -1000<=pushV[i]<=1000<br>
 * 3. pushV 的所有数字均不相同<br>
 *
 * @author c2b
 * @since 2023/3/8 17:14
 */
public class JzOffer0031IsPopOrder_M {

    public boolean IsPopOrder(int[] pushA, int[] popA) {
        Stack<Integer> stack = new Stack<>();
        int index = 0;
        for (int j : pushA) {
            // 先压入栈
            stack.push(j);
            while (!stack.empty() && stack.peek() == popA[index]) {
                stack.pop();
                index++;
            }
        }
        return index == popA.length;
    }

    public static void main(String[] args) {
        JzOffer0031IsPopOrder_M jzOffer0031IsPopOrder = new JzOffer0031IsPopOrder_M();
        jzOffer0031IsPopOrder.IsPopOrder(new int[]{1, 2, 3, 4, 5}, new int[]{4,5,3,2,1});
    }
}
